package com.android.kalaha;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;



public class Launch extends Activity{
	private SharedPreferences preferences;
	private SharedPreferences.OnSharedPreferenceChangeListener onChangeListener;
    ProgressDialog dialog;
    int increment;
 	
	/** Called when the activity is first created. */
	public Cupboard cupboard  = null;
	
	@Override
    public void onDestroy() {
		preferences.unregisterOnSharedPreferenceChangeListener(onChangeListener);
		super.onDestroy();        
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Initialize Preferences
        // Preference Listener
        onChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		        public void onSharedPreferenceChanged(
	    	            SharedPreferences preferences , String key) {
	    	        	
			        	 if (key.equals("beanamount")) {
			        		 String beanamount = preferences.getString(key,"4");
			        		 Launch.this.cupboard.set_beanamount(beanamount);
			             }
			        	 if (key.equals("earlyshowdown")) {
			        		 Boolean earlyshowdown = preferences.getBoolean(key, false);
			        		 Launch.this.cupboard.set_earlyshowdown(earlyshowdown);
			             }
			        	 if (key.equals("actorone")) {
			        		 Player player = Launch.this.cupboard.get_player(0);
			        		 player.set_actor(preferences.getString(key, "0"));			        
			        		 Launch.this.cupboard.redraw_cups();
			        	 }
			        	 if (key.equals("actortwo")) {
			        		 Player player = Launch.this.cupboard.get_player(1);
			        		 player.set_actor(preferences.getString(key, "1"));
			        		 Launch.this.cupboard.redraw_cups();
			             }	
	    	        }
	    	    };

	    preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences.registerOnSharedPreferenceChangeListener(onChangeListener);        

		// Initialize Game
        this.initialize_game();

        return;
	}
	
    private void initialize_game(){

        this.cupboard  = new Cupboard(this);
        
        // bean amount
        this.cupboard.set_beanamount(preferences.getString("beanamount","4"));
        // early showdown
        this.cupboard.set_earlyshowdown(preferences.getBoolean("earlyshowdown", false));

	    // add cups to cupboard class
	    Button btncup = (Button) findViewById(R.id.cup1);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup2);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup3);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup4);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup5);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup6);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup7);
	    this.cupboard.add_cup(btncup, true);
	    btncup = (Button) findViewById(R.id.cup8);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup9);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup10);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup11);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup12);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup13);
	    this.cupboard.add_cup(btncup);
	    btncup = (Button) findViewById(R.id.cup14);
	    this.cupboard.add_cup(btncup, true);
	
	    // add players to cupboard class
	    Button btnplayer = (Button) findViewById(R.id.player1);
	    Player player = this.cupboard.add_player(btnplayer);
	    player.set_actor(preferences.getString("actorone", "0"));
	    
	    btnplayer = (Button) findViewById(R.id.player2);
	    player = this.cupboard.add_player(btnplayer);
	    player.set_actor(preferences.getString("actortwo", "1"));
	    
	    this.cupboard.redraw();
	    return;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	// This method is called once the menu is selected
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// Menu Options
		case R.id.preferences:
			// Launch Preference activity
			Intent i = new Intent(Launch.this, Preferences.class);
			startActivity(i);
			break;
			
		// Finish App	
		case R.id.shutdown:
			this.finish();
			break;

		// Restart / Start Game
		case R.id.newgame:
			
			// in case of warning, error or something, show message
			this.cupboard.newgame();
			if(this.cupboard.get_message().length()>0){
				this.post_message(this.cupboard.get_message());
			}
			break;
		}
		return true;
	}

	public void onCupClick(View v) { 
    	Button button = (Button) v;

    	// identify cup
		Cup cup = this.cupboard.find_cup_by_button(button);
		if (cup==null){
			Log.d("ERROR", "cup is not found");
			this.cupboard.set_message("ERROR: Cup not found");
		}else{
			if(this.cupboard.take_cup(cup)){
				this.cupboard.engine();
			}
		}
		this.cupboard.redraw();
    	
		// in case of warning, error or something, show message
		if(this.cupboard.get_message().length()>0){
			this.post_message(this.cupboard.get_message());
		}
	}
	
	public void onPlayerClick(View v){

		
		if(!this.cupboard.get_game_over()){
			Cup cup = this.cupboard.help();
			String msg = "Cup " + cup.get_label() + " seems to be tha best!";
			Toast.makeText(this, msg, msg.length()).show();		
		}
	}
	
	private void post_message(String postit){
		Toast.makeText(this, postit, postit.length()).show();
		this.cupboard.set_message("");
	}
	 
    public void loading() {
 
        // convert the text value to a integer
        increment = 1;
 
        dialog = new ProgressDialog(this);
        dialog.setCancelable(true);
        dialog.setMessage("Loading...");
        // set the progress to be horizontal
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        // reset the bar to the default value of 0
        dialog.setProgress(0);
 
        // get the maximum value
        int maximum = 5;
        // set the maximum value
        dialog.setMax(maximum);
        // display the progressbar
        dialog.show();
 
        // create a thread for updating the progress bar
        Thread background = new Thread (new Runnable() {
           public void run() {
               try {
                   // enter the code to be run while displaying the progressbar.
                   //
                   // This example is just going to increment the progress bar:
                   // So keep running until the progress value reaches maximum value
                   while (dialog.getProgress()<= dialog.getMax()) {

                	   Thread.sleep(500);
                	   cupboard.evaluation.evaluate();
                	   dialog.dismiss();

                       // active the update handler
                       progressHandler.sendMessage(progressHandler.obtainMessage());
                   }

               } catch (java.lang.InterruptedException e) {
                   // if something fails do something smart
               }
           }
        });
 
        // start the background thread
        background.start();
 
    }
 
    // handler for the background updating
    Handler progressHandler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.incrementProgressBy(increment);
        	if(dialog.getProgress()== dialog.getMax())
        	{
        		dialog.dismiss();
        	}
       }
    };

}